package com.ljkj.cordial.chat.presenter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.activity.FriendInfoActivity;
import com.ljkj.cordial.chat.activity.PersonalActivity;
import com.ljkj.cordial.chat.adapter.ChatAdapter;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.ChatTableUnit;
import com.ljkj.cordial.chat.bean.PayLoad;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.nic.view.util.glide.GlideUtil;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public abstract class AChatPresenter {

    public final static int LEFT = 0;
    public final static int RIGHT = 1;
    public final static int TEXT = 2;
    public final static int FILE = 3;
    public final static int PICTURE = 4;
    public final static int VIDEO = 5;
    public final static int VOICE = 6;
    public final static int EMOJI = 7;
    public final static int READ_FINISH = 8;
    public final static int HISTORY_TIME = 9;
    public final static int DEL_CHAT_MSG = 10;
    private int direction;
    private int chatType = Canstants.GROUP_CHAT;
    private DataSetGetter mDataSetGetter;
    /**
     * 是否允许装载数据，用于滑动刷问题
     */
    private boolean isLoadAccess = true;

    public boolean isLoadAccess() {
        return isLoadAccess;
    }

    public AChatPresenter setLoadAccess(boolean loadAccess) {
        isLoadAccess = loadAccess;
        return this;
    }

    public int getChatType() {
        return chatType;
    }

    public AChatPresenter setChatType(int chatType) {
        this.chatType = chatType;
        return this;
    }

    public AChatPresenter setDirection(int direction) {
        this.direction = direction;
        return this;
    }

    public AChatPresenter setDataSetGetter(DataSetGetter getter) {
        this.mDataSetGetter = getter;
        return this;
    }

    public AChatPresenter(int direction) {
        this.direction = direction;

    }

    public int getDirection() {
        return direction;
    }

    public abstract RecyclerView.ViewHolder getViewHolder(View view);

    public abstract void bindViewHolder(RecyclerView.ViewHolder holder, Object obj, int position);

    public void bindViewHolder(ChatAdapter chatAdapter, int position, RecyclerView.ViewHolder holder, Object obj, PayLoad payLoad) {
    }

    private OnChatViewItemClickListener onChatViewResultListener;

    public OnChatViewItemClickListener getOnCListener() {
        return onChatViewResultListener;
    }

    public AChatPresenter setOnChatViewResultListener(OnChatViewItemClickListener onChatViewResultListener) {
        this.onChatViewResultListener = onChatViewResultListener;
        return this;
    }

    /**
     * @param checkBox
     * @param isCheck
     */
    public void setCheck(CheckBox checkBox, boolean isCheck) {
        checkBox.setChecked(isCheck);
    }

    /**
     * @param checkBox
     * @param isVisible
     */
    public void setVisible(CheckBox checkBox, boolean isVisible) {
        if (isVisible) {
            checkBox.setVisibility(View.VISIBLE);
        } else {
            checkBox.setVisibility(View.GONE);
        }
    }


    public void loadAvatar(ChatTableUnit item, ImageView iv) {
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.getTargetId().equals(UserPreferences.getUserId())) {
                    v.getContext().startActivity(new Intent(v.getContext(), PersonalActivity.class));
                } else if (FriendTable.isExistFriendById(item.getTargetId())) {
                    String userType = IMSUtils.userTypeAnalysis(item.getTargetId());
                    FriendInfoActivity.jumpTo(v.getContext(), IMSContacts.UserType.REGISTERED_USER.equals(userType) ? Canstants.KEY_REGISTER : Canstants.KEY_VISITOR, item.getTargetName(), item.getTargetId(), userType);
                } else {
                    FriendInfoActivity.jumpTo((Activity) v.getContext(), item.getGroupId(), item.getTargetName(), item.getTargetId());
                }

//                if (item.getTargetId().equals(ChatApp.getInstance().getUserId())) {
//                    v.getContext().startActivity(new Intent(v.getContext(), PersonalActivity.class));
//                } else if (FriendTable.isExistFriendById(item.getTargetId())) {
//                    if (item.getFromType() == Canstants.GROUP_CHAT) {
//                        FriendInfoActivity.jumpTo((Activity) v.getContext(), item.getGroupId(), item.getTargetName(), item.getTargetId());
//                    } else {
//                        FriendInfoActivity.jumpTo(v.getContext(), Canstants.KEY_REGISTER, item.getTargetName(), item.getTargetId(), item.getTargetType());
//                    }
//                } else {
//                    SearchBean search = new SearchBean();
//                    search.setGroupId(item.getGroupId());
//                    if (IMSContacts.UserType.REGISTERED_USER.equals(item.getTargetType())) {
//                        search.setUserId(item.getTargetId());
//                    } else {
//                        search.setTouristId(item.getTargetId());
//                    }
//                    search.setAvatars(item.getChatAvatarUrl());
//                    search.setName(item.getTargetName());
//                    SearchResultActivity.jumpTo((Activity) v.getContext(), Canstants.KEY_SEARCH_FRIEND, search);
//                }

            }
        });
        iv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (longItemClickListener != null) {
                    longItemClickListener.onLongClick(v, item);
                    return true;
                }
                return false;
            }
        });
        if (!TextUtils.isEmpty(item.getChatAvatarPath())) {
            setFriendPath(iv, item.getChatAvatarPath(), item.getChatAvatarUrl());
        } else {
            if (!TextUtils.isEmpty(item.getChatAvatarUrl())) {
                AlbumManageUtil.getInstance().downLoadFileFriend(item.getChatAvatarUrl(), item.getTargetId(), iv);
            } else {
                GlideUtil.getInstance().load(R.mipmap.pic_user_avatar_default_36dp, iv);
            }
        }


//        if (item.getTargetId().equals(UserPreferences.getUserId())) {
//            ImageLoader.getInstance().displayUserAvatar(item.getChatAvatarUrl(), iv);
//        } else {
//            if (item.getFromType() == Canstants.GROUP_CHAT) {
//                ImageLoader.getInstance().displayGroupMemberAvatar(item.getGroupId(), item.getTargetId(), item.getChatAvatarUrl(), iv);
//            } else {
//                ImageLoader.getInstance().displayFriendAvatar(item.getTargetId(), item.getChatAvatarUrl(), iv);
//            }
//        }
    }

    public void setFriendPath(ImageView iv, String path, String url) {
        String tag = (String) iv.getTag(com.nic.view.R.id.glide_image_id);
        if (TextUtils.isEmpty(tag) || tag.equals(url)) {
            iv.setTag(com.nic.view.R.id.glide_image_id, url);
        }
        GlideUtil.getInstance().load(path, iv);
    }

    public interface OnLongItemClickListener {
        void onLongClick(View v, ChatTableUnit item);
    }

    private OnLongItemClickListener longItemClickListener;

    public void setLongItemClickListener(OnLongItemClickListener longItemClickListener) {
        this.longItemClickListener = longItemClickListener;
    }

    /**
     * 展示缩略图
     *
     * @param item
     * @param imageView
     */
    public void showThumbPicture(ChatTableUnit item, ImageView imageView, int position) {

//        String thumbPath = null;
//        if (!TextUtils.isEmpty(item.getThumbPath())) {
//            thumbPath = item.getThumbPath();
//        } else {
//            if (!TextUtils.isEmpty(item.getAlbumId()) && Long.parseLong(item.getAlbumId()) > 0) {
//                AlbumTableBean al = AlbumTableBean.queryById(Long.parseLong(item.getAlbumId()));
//                thumbPath = al != null ? al.getMThumbPath() : null;
//            }
//        }
        if (!TextUtils.isEmpty(item.getThumbPath())) {
            String tag = (String) imageView.getTag(com.nic.view.R.id.glide_image_id);
            if (TextUtils.isEmpty(tag) || tag.equals(item.getThumbPath())) {
//                imageView.setImageBitmap(BitmapFactory.decodeFile(item.getThumbPath()));
                imageView.setTag(com.nic.view.R.id.glide_image_id, item.getThumbPath());
            }
            File file = new File(item.getThumbPath());
            if (!file.exists()) {
                int dpw = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 94.5f, imageView.getResources().getDisplayMetrics());
                int dph = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 168f, imageView.getResources().getDisplayMetrics());
                imageView.getLayoutParams().width = dpw;
                imageView.getLayoutParams().height = dph;
                imageView.setBackgroundColor(ContextCompat.getColor(imageView.getContext(), R.color.gray3));
                observerFileState(item, position);
            } else {
                setImageViewSize(imageView, item.getThumbPath());
                GlideUtil.getInstance().loadSmallRadius(item.getThumbPath(), imageView);
            }
        } else {
//            GlideUtil.getInstance().clear(imageView);
            imageView.setBackgroundColor(ContextCompat.getColor(imageView.getContext(), R.color.gray_200));
            observerFileState(item, position);
        }
    }

    public void observerFileState(ChatTableUnit item, int position) {
        if (onFileNoExistListener != null) {
            onFileNoExistListener.onCall(item, position);
        }
    }

    /**
     * 展示缩略图站位
     *
     * @param item
     * @param imageView
     */
    public static void showThumbPictureDef(ChatTableUnit item, ImageView imageView) {
        if (!TextUtils.isEmpty(item.getThumbPath())) {
            File file = new File(item.getThumbPath());
            if (!file.exists()) {
                int dpw = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 94.5f, imageView.getResources().getDisplayMetrics());
                int dph = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 168f, imageView.getResources().getDisplayMetrics());
                imageView.getLayoutParams().width = dpw;
                imageView.getLayoutParams().height = dph;
                imageView.setBackgroundColor(ContextCompat.getColor(imageView.getContext(), R.color.gray3));
            } else {
                setImageViewSize(imageView, item.getThumbPath());
                GlideUtil.getInstance().load(R.drawable.bg_white_rec, imageView);
            }
        } else {
            imageView.setBackgroundColor(ContextCompat.getColor(imageView.getContext(), R.color.gray_200));
        }
    }

    public void setReadFinishState(TextView textView, boolean isReadFinish) {
        if (isReadFinish) {
            textView.setVisibility(View.VISIBLE);
        } else {
            textView.setVisibility(View.GONE);
        }
    }

    private static void setImageViewSize(ImageView imageView, String thumbPath) {
        int dpw = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 94.5f, imageView.getResources().getDisplayMetrics());
        int dpm = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 126f, imageView.getResources().getDisplayMetrics());
        int dph = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 168f, imageView.getResources().getDisplayMetrics());
        int dpxh = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 204.75f, imageView.getResources().getDisplayMetrics());
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(thumbPath, options);
        float d = (float) Math.min(options.outHeight, options.outWidth) / (float) Math.max(options.outHeight, options.outWidth);
        if (options.outHeight > options.outWidth) {
            imageView.getLayoutParams().width = dpw;
            imageView.getLayoutParams().height = (int) (dpw / d);
        } else if (options.outHeight == options.outWidth) {
            imageView.getLayoutParams().width = dpm;
            imageView.getLayoutParams().height = dpm;
        } else {
            double s9195 = new BigDecimal(9f / 19.5f).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            double wh = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            if (wh == s9195) {
                imageView.getLayoutParams().width = dpxh;
                imageView.getLayoutParams().height = (int) (dpxh * d);
            } else {
                imageView.getLayoutParams().width = dph;
                imageView.getLayoutParams().height = (int) (dph * d);
            }
        }

    }

    public void refreshSendState(ChatTableUnit item, ContentLoadingProgressBar chatItemProgress, ImageView imageView, TextView downTimeTv) {
        imageView.setVisibility(View.GONE);
        downTimeTv.setVisibility(View.GONE);
        if (item.getSendState() == ChatTableUnit.SEND_ING) {
            chatItemProgress.show();
        } else if (item.getSendState() == ChatTableUnit.SEND_SUCCESS) {
            imageView.setVisibility(View.GONE);
            if (item.isStartReadFinish()) {
                downTimeTv.setVisibility(View.VISIBLE);
            } else {
                downTimeTv.setVisibility(View.GONE);
            }
            chatItemProgress.hide();
        } else if (item.getSendState() == ChatTableUnit.SEND_FAIL) {
            chatItemProgress.hide();
            downTimeTv.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
        }
    }

    public List<ChatTableUnit> getDataSet() {
        if (mDataSetGetter != null)
            return mDataSetGetter.getDataSet();
        else
            return new ArrayList<>();
    }

    public RecyclerView getRecyclerView() {
        if (mDataSetGetter != null)
            return mDataSetGetter.getRecyclerView();
        return null;
    }

    public interface DataSetGetter {
        List<ChatTableUnit> getDataSet();

        RecyclerView getRecyclerView();
    }

    public static void setProgressColor(ContentLoadingProgressBar chatItemProgress) {
        chatItemProgress.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(chatItemProgress.getContext(), R.color.gray_300), PorterDuff.Mode.MULTIPLY);
        chatItemProgress.hide();
    }

    private OnFileNoExistListener onFileNoExistListener;

    public void setOnFileNoExistListener(OnFileNoExistListener onFileNoExistListener) {
        this.onFileNoExistListener = onFileNoExistListener;
    }

    public interface OnFileNoExistListener {
        void onCall(ChatTableUnit item, int position);
    }
}
